//
//  OMCTableViewController.m
//  OMCServiceDemoApp
//
//  Created by GuochengLiu on 2017/9/24.
//  Copyright © 2017年 sumavision. All rights reserved.
//

#import "OMCTableViewController.h"
#import <OMCService/OMCService.h>
#import "CustomURLController.h"
#import "InterfaceModel.h"
#import "InterfaceController.h"

#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)

typedef NS_ENUM(NSInteger, sections) {
    baseData = 0,
    vod,
    live,
    user,
    uba,
    pay
};


@interface OMCTableViewController ()

@end

@implementation OMCTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [OMCApiBaseManager sharedManager].omc_pLocation = @"001";
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    // 添加右上角
    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithTitle:@"自定义URL" style:UIBarButtonItemStylePlain target:self action:@selector(customBarBtnTouched)];
    self.navigationItem.rightBarButtonItem = customItem;
    // 添加左上角
    UIBarButtonItem *autoItem = [[UIBarButtonItem alloc] initWithTitle:@"自动测试" style:UIBarButtonItemStylePlain target:self action:@selector(autoBarBtnTouched)];
    self.navigationItem.leftBarButtonItem = autoItem;
    
    // 初始化基础数据接口
    NSString         *path = [[NSBundle mainBundle] pathForResource:@"CommonInterfaces.plist" ofType:nil];
    NSArray         *array = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:0];
    int index = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        ifm.ID = [NSString stringWithFormat:@"1.%d", index];
        [arrayM addObject:ifm];
    }
    
    commonArr = arrayM;
    
    // 初始化点播接口
    path   = [[NSBundle mainBundle] pathForResource:@"VodInterfaces.plist" ofType:nil];
    array  = [NSArray arrayWithContentsOfFile:path];
    arrayM = [NSMutableArray arrayWithCapacity:0];
    index  = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        ifm.ID = [NSString stringWithFormat:@"2.%d", index];
        [arrayM addObject:ifm];
    }
    
    vodArr = arrayM;
    
    // 初始化直播接口
    path   = [[NSBundle mainBundle] pathForResource:@"LiveInterfaces.plist" ofType:nil];
    array  = [NSArray arrayWithContentsOfFile:path];
    arrayM = [NSMutableArray arrayWithCapacity:0];
    index  = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        //        ifm.ID = [NSString stringWithFormat:@"3.%d", index];
        [arrayM addObject:ifm];
    }
    
    liveArr = arrayM;
    
    // 初始化用户接口
    path   = [[NSBundle mainBundle] pathForResource:@"UserInterfaces.plist" ofType:nil];
    array  = [NSArray arrayWithContentsOfFile:path];
    arrayM = [NSMutableArray arrayWithCapacity:0];
    index  = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        //        ifm.ID = [NSString stringWithFormat:@"4.%d", index];
        [arrayM addObject:ifm];
    }
    
    userArr = arrayM;
    
    // 初始化UBA接口
    path   = [[NSBundle mainBundle] pathForResource:@"UBAInterfaces.plist" ofType:nil];
    array  = [NSArray arrayWithContentsOfFile:path];
    arrayM = [NSMutableArray arrayWithCapacity:0];
    index  = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        //        ifm.ID = [NSString stringWithFormat:@"5.%d", index];
        [arrayM addObject:ifm];
    }
    
    ubaArr = arrayM;
    
    // 初始化支付接口
    path   = [[NSBundle mainBundle] pathForResource:@"PayInterfaces.plist" ofType:nil];
    array  = [NSArray arrayWithContentsOfFile:path];
    arrayM = [NSMutableArray arrayWithCapacity:0];
    index  = 0;
    
    for (NSDictionary *interface in array)
    {
        index++;
        InterfaceModel *ifm = [InterfaceModel interfaceWithDic:interface];
        //        ifm.ID = [NSString stringWithFormat:@"6.%d", index];
        [arrayM addObject:ifm];
    }
    
    payArr = arrayM;
    
    [InterfaceMethods sharedMethod].delegate = self; // 更新cell
    
    
    [self.tableView reloadData];
}

// 触发自定义URL
- (void)customBarBtnTouched
{
    [self.navigationController pushViewController:[[CustomURLController alloc] init] animated:YES];
}

#pragma mark - 触发自动测试
- (void)autoBarBtnTouched
{
    for (int i=0; i<commonArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!commonArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:commonArr[i].sendMethod]);
        }
    }
    for (int i=0; i<vodArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!vodArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:vodArr[i].sendMethod]);
        }
    }
    for (int i=0; i<liveArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!liveArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:liveArr[i].sendMethod]);
        }
    }
    for (int i=0; i<userArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!userArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:userArr[i].sendMethod]);
        }
    }
    for (int i=0; i<ubaArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!ubaArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:ubaArr[i].sendMethod]);
        }
    }
    for (int i=0; i<payArr.count; i++)
    {
        // 只执行没有被依赖的接口
        if (!payArr[i].relied)
        {
            SuppressPerformSelectorLeakWarning([self sendRequestWith:payArr[i].sendMethod]);
        }
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = @"";
    switch (section) {
        case 0:
            title = @"Portal-基础数据";
            break;
        case 1:
            title = @"Portal-点播";
            break;
        case 2:
            title = @"Portal-直播";
            break;
        case 3:
            title = @"Portal-用户";
            break;
        case 4:
            title = @"Portal-UBA";
            break;
        case 5:
            title = @"Portal-支付";
            break;
        default:
            break;
    }
    
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 0;
    
    switch (section) {
        case baseData:
            count = [commonArr count];
            break;
        case vod:
            count = [vodArr count];
            break;
        case live:
            count = [liveArr count];
            break;
        case user:
            count = [userArr count];
            break;
        case uba:
            count = [ubaArr count];
            break;
        case pay:
            count = [payArr count];
            break;
        default:
            break;
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Ivideo_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"customCell"];
    
    switch (indexPath.section) {
        case baseData:
            if (indexPath.row < commonArr.count)
            {
                cell.model = commonArr[indexPath.row];
            }
            break;
        case vod:
            if (indexPath.row < vodArr.count)
            {
                cell.model = vodArr[indexPath.row];
            }
            break;
        case live:
            if (indexPath.row < liveArr.count)
            {
                cell.model = liveArr[indexPath.row];
            }
            break;
        case user:
            if (indexPath.row < userArr.count)
            {
                cell.model = userArr[indexPath.row];
            }
            break;
        case uba:
            if (indexPath.row < ubaArr.count)
            {
                cell.model = ubaArr[indexPath.row];
            }
            break;
        case pay:
            if (indexPath.row < payArr.count)
            {
                cell.model = payArr[indexPath.row];
            }
            break;
        default:
            break;
    }
    
    InterfaceModel *model = cell.model;
    
    // 设置subtitle高度
    NSString *str = [model.requestURL componentsSeparatedByString:@"?"][0];
    CGRect   rect = cell.subtitleLabel.frame;
    rect.size.height         = [self heightForCell:cell Subtitle:str];
    cell.subtitleLabel.frame = rect;
    cell.subtitleLabel.text  = str;
    cell.titleLabel.text     = [NSString stringWithFormat:@"%@ %@", model.ID, model.interfaceDes];
    
    // 是否显示依赖
    if (![model.rely isEqualToString:@""])
    {
        cell.relyLabel.text = [NSString stringWithFormat:@"依赖: %@", model.rely];
    }
    else
    {
        cell.relyLabel.text = @"";
    }
    
    // 设置状态
    switch (model.status) {
        case 0: // 未测试
            cell.sendButton.enabled = YES;
            cell.statusView.backgroundColor = [UIColor grayColor];
            break;
        case 1: // 测试中
        {
            cell.sendButton.enabled = NO;
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            indicator.center = CGPointMake(8, 8);
            cell.statusView.backgroundColor = [UIColor whiteColor];
            [cell.statusView addSubview:indicator];
            [indicator startAnimating];
        }
            break;
        case 2: // 失败
            cell.sendButton.enabled = YES;
            cell.statusView.backgroundColor = [UIColor redColor];
            if (cell.statusView.subviews.count > 0) {
                [cell.statusView.subviews[0] removeFromSuperview];
            }
            break;
        case 3: // 成功
            cell.sendButton.enabled = YES;
            cell.statusView.backgroundColor = [UIColor greenColor];
            break;
        default:
            break;
    }
    
    cell.delegate = self;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    InterfaceModel *model;
    
    switch (indexPath.section)
    {
        case baseData:
            if (indexPath.row < commonArr.count)
            {
                model = commonArr[indexPath.row];
            }
            break;
        case vod:
            if (indexPath.row < vodArr.count)
            {
                model = vodArr[indexPath.row];
            }
            break;
        case live:
            if (indexPath.row < liveArr.count)
            {
                model = liveArr[indexPath.row];
            }
            break;
        case user:
            if (indexPath.row < userArr.count)
            {
                model = userArr[indexPath.row];
            }
            break;
        case uba:
            if (indexPath.row < ubaArr.count)
            {
                model = ubaArr[indexPath.row];
            }
            break;
        case pay:
            if (indexPath.row < payArr.count)
            {
                model = payArr[indexPath.row];
            }
            break;
        default:
            break;
    }
    
    InterfaceController *interfaceController = [[InterfaceController alloc] initWithModel:model];
    interfaceController.delegate = self;
    interfaceController.indexPath = indexPath;
    if (model.responseArr)
    {
        [interfaceController.responsePicker selectRow:model.pickerSelectedRow inComponent:0 animated:YES];
    }
    interfaceController.segmentedControl.selectedSegmentIndex = model.segmentIndex;
    
    [self.navigationController pushViewController:interfaceController animated:YES];
}

- (CGFloat)heightForCell: (Ivideo_TableViewCell *)cell Subtitle: (NSString *)content {
    CGRect rect = [content boundingRectWithSize:CGSizeMake(cell.subtitleLabel.bounds.size.width, MAXFLOAT)
                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10]} context:nil];
    
    return rect.size.height;
}

#pragma mark - 代理方法
- (void)updateCellAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.tableView cellForRowAtIndexPath:indexPath])
    {
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)updateParamsDicWith:(NSDictionary *)paramsDic atIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case baseData:
        {
            if (indexPath.row < commonArr.count)
            {
                InterfaceModel *model = commonArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        case vod:
        {
            if (indexPath.row < vodArr.count)
            {
                InterfaceModel *model = vodArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        case live:
        {
            if (indexPath.row < liveArr.count)
            {
                InterfaceModel *model = liveArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        case user:
        {
            if (indexPath.row < userArr.count)
            {
                InterfaceModel *model = userArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        case uba:
        {
            if (indexPath.row < ubaArr.count)
            {
                InterfaceModel *model = ubaArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        case pay:
        {
            if (indexPath.row < payArr.count)
            {
                InterfaceModel *model = payArr[indexPath.row];
                model.paramsDic = [NSMutableDictionary dictionaryWithDictionary:paramsDic];
            }
        }
            break;
        default:
            break;
    }
}

- (void)setPickerRowWith:(NSInteger)row atIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case baseData:
        {
            if (indexPath.row < commonArr.count)
            {
                InterfaceModel *model = commonArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        case vod:
        {
            if (indexPath.row < vodArr.count)
            {
                InterfaceModel *model = vodArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        case live:
        {
            if (indexPath.row < liveArr.count)
            {
                InterfaceModel *model = liveArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        case user:
        {
            if (indexPath.row < userArr.count)
            {
                InterfaceModel *model = userArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        case uba:
        {
            if (indexPath.row < ubaArr.count)
            {
                InterfaceModel *model = ubaArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        case pay:
        {
            if (indexPath.row < payArr.count)
            {
                InterfaceModel *model = payArr[indexPath.row];
                model.pickerSelectedRow = row;
            }
        }
            break;
        default:
            break;
    }
}


- (void)sendRequestWith:(SEL)selector {
    SuppressPerformSelectorLeakWarning(
                                       if ([[InterfaceMethods sharedMethod] respondsToSelector:selector])
                                       {
                                           [[InterfaceMethods sharedMethod] performSelector:selector];
                                       }
                                       );
}

//- (void)testInterface: (InterfaceBaseController *)interface withInterfaces: (NSArray <InterfaceBaseController *> *)interfaces {
//    // 如果没有依赖
//    if ([interface.rely isEqualToString:@""]) {
//        SuppressPerformSelectorLeakWarning([interface performSelector:interface.sendMethod];);
//    }
//    // 如果有依赖
//    else {
//        // 拿到所依赖的接口的编号
//        NSArray *arr = [interface.rely componentsSeparatedByString:@", "]; // ["x.y",...]
//        NSInteger index = 0;
//        NSInteger x = 0;
//        NSInteger y = 0;
//        // 遍历所有依赖接口
//        for (int j=0; j<arr.count; j++) {
//            NSArray *rely = [arr[j] componentsSeparatedByString:@"."]; // ["x","y"]
//
//            x = [rely[0] integerValue];
//            y = [rely[1] integerValue];
//
//            switch (x) {
//                case 1: // commonInterface
//                    index = y - 1;
//                    break;
//                case 2: // vodInterface
//                    index = commonArr.count + y - 1;
//                    break;
//                case 3: // liveInterface
//                    index = commonArr.count + self.vodInterfaces.count + y - 1;
//                    break;
//                default:
//                    break;
//            }
//
//            dispatch_group_t group = dispatch_group_create();
//            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_group_async(group, queue, ^{
//                // 先执行所依赖的接口
//                [self testInterface:interfaces[index] withInterfaces:interfaces];
//            });
//            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//                // 再执行自己
//                SuppressPerformSelectorLeakWarning([interface performSelector:interface.sendMethod];);
//            });
//        }
//    }
//}


//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//    if ([segue.identifier isEqualToString:@"showDetailView"]) {
//        Ivideo_TableViewCell *cell = sender;
//
//        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//
//        FeedbackMode *mode = self.interfaceModes[indexPath.row];
//
//        Ivideo_DetailViewController *detailViewController = [segue destinationViewController];
//
//        [detailViewController.viewArray insertObject:mode.requestView atIndex:1];
//        detailViewController.indexPath = indexPath;
//        detailViewController.responseText.text = [NSString stringWithFormat:@"%@", mode.responseData];
//    }
//}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


@end
